const express = require('express');
const mysql = require('mysql');
const router = express.Router();
// 导入模型
const User = require('../models/user');
const Recommend = require('../models/recommend');
const Movie = require('../models/movie');
const Article = require('../models/article');
const Comment = require('../models/comment');
// 导入中间件
const { idValidatorBody, idValidatorParam } = require('../validators/userValidator');
const auth = require('../middleware/authMiddleware');
const validate = require('../middleware/validatorMiddleware');

const db = mysql.createConnection(
    {user: "root",
    password: "gomx1028",
    database: "test",
    host: '127.0.0.1'}
);
//query poem
router.get('/showPoem', (req, res)=>{
    db.query("select * from poem order by rand() limit 3", (err, result)=>{
    if (err){return res.json({status: 1, message: err})  };
    console.log(result);
    return res.json({status: 1, message: "获取成功", data: result});
    });
});

// 显示主页推荐
router.get('/showIndex', async (req, res) => {
  const result = await Recommend.findAll();
  res.json({ status: 0, message: '获取推荐成功', data: result })
});

// 显示电影详情
router.post('/showMovieDetail', idValidatorBody, validate, async (req, res) => {
  const movie = await Movie.findByID(req.body.id);
  if (!movie) {
    return res.json({ status: 1, message: '电影不存在' });
  }
  return res.json({ status: 0, message: '获取电影详情成功', data: movie })
});

router.get('/movies/:id', async (req, res) => {
  const movie = await Movie.query({ "_id": req.params.id });
  if (!movie) {
    return res.json({ status: 1, message: '电影不存在' });
  }
  return res.json({ status: 0, message: '获取电影详情成功', data: movie })
});

// 显示评论列表
router.post('/showCommentList', idValidatorBody, validate, async (req, res) => {
  const movie_id = req.body.id;
  const comments = await Comment.query({ "movie_id": movie_id });
  if (!comments) {
    return res.json({ status: 1, message: '评论不存在' });
  }

  return res.json({ status: 0, message: '获取评论列表成功', data: comments })
});

// 显示所有排行榜， 电影字段
router.get('/showRank', async (req, res) => {
  const result = await Movie.findAll();
  // return res.render('index.pug', { title: '排行榜', movies: result });
  return res.json({ status: 0, message: '获取排行榜成功', data: result })
});

// 显示文章列表
router.get('/showArticleList', async (req, res) => {
  const result = await Article.findAll();
  res.json({ status: 0, message: '获取文章列表成功', data: result })
});

// 显示文章内容
router.post('/showArticleDetail', idValidatorBody, validate, auth, async (req, res) => {
  const article_id = req.body.id;
  const article = await Article.findByID(article_id);
  if (!article) {
    return res.json({ status: 1, message: '文章不存在' });
  }
  return res.json({ status: 0, message: '获取文章内容成功', data: article })
});

// 显示用户个人信息
router.post('/showUserList', auth, async (req, res) => {
  const result = await User.findAll();
  return res.json({ status: 0, message: '获取所有用户信息成功', data: result });
});

module.exports = router;

